package com.example.controller;

import com.example.aop.Log;
import com.example.entity.Person;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
https://mp.weixin.qq.com/s?__biz=Mzk0MjMyNTIzOQ==&mid=2247484877&idx=1&sn=6f7b24568be3f657290abe57ea1ecc17&chksm=c2c5a955f5b220436bd273bebe392c0729792bb8a9ece48f1654da75352478597d75fba1f93a&mpshare=1&scene=1&srcid=1128ZnLKj8U3cTwlGhYPpnHr&sharer_shareinfo=5f4961ba3ab28548821ed07e5c283dce&sharer_shareinfo_first=78a5d3e3aecae7903a92396e16089c33#rd
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Log
    @RequestMapping("/getPage")
    public String getPage(@RequestParam("projectId") String projectId) {

        return "hello";
    }

    public static void main(String[] args) throws Exception {
        Person beforePerson = new Person();
        beforePerson.setAge(18L);
        beforePerson.setName("Tom");
        Person afterPerson = new Person();
        afterPerson.setAge(18L);
        afterPerson.setName("Bom");
        fieldCompare(beforePerson,afterPerson);
    }
    //使用field对象来处理
    private static void fieldCompare(Object beforeObj ,Object afterObj) throws  Exception{
        Field[] beforeFields = beforeObj.getClass().getDeclaredFields();
        Field[] afterFields = afterObj.getClass().getDeclaredFields();
        Field.setAccessible(beforeFields, true); //设置私有属性可以访问到
        Field.setAccessible(afterFields, true);
        //循环遍历比较属性
        if(beforeFields != null && beforeFields.length > 0){
            for(int i=0; i<beforeFields.length; i++){
                Object beforeValue = beforeFields[i].get(beforeObj); //取出对应的属性值
                Object afterValue = afterFields[i].get(afterObj);
                StringBuffer differentBuf=new StringBuffer();
                if((beforeValue != null && !"".equals(beforeValue) && !beforeValue.equals(afterValue)) || ((beforeValue == null || "".equals(beforeValue)) && afterValue != null)){
                    differentBuf.append("字段:").append( beforeFields[i].getName())
                            .append("原值为:").append(beforeValue)
                            .append("现值为:").append(afterValue);
                    System.out.println(differentBuf.toString());
                }
            }
        }
    }
}
